import React, { useState, useEffect, useRef } from 'react'
import { Table, message } from 'antd'
import { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import moment from 'moment'
import { awaitWrap } from '@js/tool'
import { getData } from './ajax'
import SearchForm from '@components/SearchForm/Index'
import style from './Index.module.less'
import CreateYear from './components/CreateYear'
import Arbitrators from './components/Arbitrators'

// 获取表格参数
function getColumns (addWindow) {
  return [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'index',
      align: 'center',
      width: 60
    },
    {
      title: '办案秘书',
      dataIndex: 'processer',
      key: 'processer'
    },
    {
      title: '平均延长天数',
      dataIndex: 'avg_days',
      key: 'avg_days'
    },
    {
      title: '延长申请件数',
      dataIndex: 'exnum',
      key: 'exnum'
    },
    {
      title: '操作',
      dataIndex: 'operate',
      key: 'operate',
      render: (value, line) => {
        return (<span className={style['operate-btn']} onClick={() => openDetail(addWindow, line)}>详情</span>)
      }
    }
  ]
}

const initialValues = {
  create_datetime: moment()
}

const extendParams = [
  { name: 'create_datetime', label: '申请时间', defaultVisible: true, component: CreateYear },
  { name: 'arbitrators', label: '仲裁员', defaultVisible: true, component: Arbitrators }
]

function openDetail (addWindow, data) {
  addWindow({ id: `LazyExtendTime-${data.processeruid}`, title: `超期申请延长审限-${data.processer}`, componentName: 'LazyExtendTime', forceRefresh: true, meta: { processeruid: data.processeruid } })
}

// 改变分页
function tableChange ({ current, pageSize }, setCurrent, setPageSize) {
  setCurrent(current)
  setPageSize(pageSize)
}

// 获取数据
async function getTableData (condition, current, pageSize, setTotal, setList, setLoading) {
  setLoading(true)
  const [e, d] = await awaitWrap(getData(condition))
  setLoading(false)
  if (e) {
    return message.warning(e.message)
  }
  const list = d.map((li, i) => {
    li.key = pageSize * (current - 1) + i + 1
    return li
  })
  setList(list)
  setTotal(d.length)
}

// 处理搜索表单扩展字段
function extendCondition (condition, formData) {
  const n = formData.count_inlimit
  if (n) {
    condition.push({ k: 'count_inlimit', o: n < 4 ? '=' : '>=', v: formData.count_inlimit })
  }
  if (formData.create_datetime) {
    const year = formData.create_datetime.year()
    const begin = moment(`${year}-01-01 00:00:00`)
    const end = moment(begin)
    end.add(1, 'year')
    end.subtract(1, 'second')
    condition.push({ k: 'l.create_datetime', o: '>=', v: Math.floor(begin / 1000) })
    condition.push({ k: 'l.create_datetime', o: '<=', v: Math.floor(end / 1000) })
  }
  if (formData.arbitrators) {
    condition.push({ k: 'c.arbitrators', o: 'like', v: `%${formData.arbitrators}%` })
  }
  return { condition, formData }
}

function Main ({ title, addWindow }) {
  const [ready, setReady] = useState(false)
  const [condition, setCondition] = useState([])
  const [loading, setLoading] = useState(false)
  const [list, setList] = useState([])
  const [current, setCurrent] = useState(1)
  const [pageSize, setPageSize] = useState(10)
  const [total, setTotal] = useState(0)
  const [pagination, setPagination] = useState({
    current,
    pageSize,
    total,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: total => `共 ${total} 条记录`,
    size: 'small'
  })
  const formRef = useRef(null)
  useEffect(() => {
    const c = formRef.current
    c.showAll()
    setTimeout(() => {
      c.submit()
    }, 0)
  }, [formRef])
  useEffect(() => {
    const p = pagination
    if (p.current !== current || p.pageSize !== pageSize || p.total !== total) {
      setPagination({
        ...p,
        current,
        pageSize,
        total
      })
    }
  }, [current, pageSize, pagination, total])
  useEffect(() => {
    if (ready) {
      getTableData(condition, current, pageSize, setTotal, setList, setLoading)
    }
  }, [condition, current, pageSize, ready])
  return (
    <div className={style.container}>
      <div className={style['title-line']}>
        <span>{title}</span>
      </div>
      <SearchForm ref={formRef} params={['create_datetime', 'arbitrators']} initialValues={initialValues} extendParams={extendParams} extendCondition={(c, f) => extendCondition(c, f)} onChange={d => { setCondition(d); setCurrent(1); setReady(true) }} />
      <div className={style['table-container']}>
        <Table loading={loading} columns={getColumns(addWindow)} dataSource={list} pagination={pagination} onChange={(v) => tableChange(v, setCurrent, setPageSize)} />
      </div>
    </div>
  )
}

const mapState = mapStateToProps(function (state) {
  return {

  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {

  }
})

export default connect(mapState, mapDispatch)(Main)
